package bma.common.thrift.sample;

import java.util.concurrent.Executor;

import org.apache.thrift.TException;

import bma.common.langutil.ai.stack.AIStack;
import bma.common.langutil.core.ObjectUtil;

public class HelloImpl implements Hello.Iface, Hello4AI.Iface {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(HelloImpl.class);

	private Executor executor;

	public Executor getExecutor() {
		return executor;
	}

	public void setExecutor(Executor executor) {
		this.executor = executor;
	}

	@Override
	public boolean say(final AIStack<Boolean> stack, final String word)
			throws TException {
		executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					say(word);
					stack.success(true);
				} catch (Exception e) {
					stack.failure(e);
				}

			}
		});
		return false;
	}

	@Override
	public boolean name(final AIStack<String> stack, final String title)
			throws TException {
		executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					stack.success(name(title));
				} catch (Exception e) {
					stack.failure(e);
				}

			}
		});
		return false;
	}

	@Override
	public boolean error(final AIStack<Boolean> stack, final String msg)
			throws TException {
		executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					error(msg);
					stack.success(true);
				} catch (Exception e) {
					stack.failure(e);
				}

			}
		});
		return false;
	}

	@Override
	public boolean sleep(final AIStack<Boolean> stack, final int time)
			throws TException {
		executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					ObjectUtil.waitFor(this, time);
					stack.success(true);
				} catch (Exception e) {
					stack.failure(e);
				}

			}
		});
		return false;
	}

	@Override
	public void say(String word) throws TException {
		log.info("hello " + word);
	}

	@Override
	public String name(String title) throws TException {
		return "hello " + title;
	}

	@Override
	public void error(String msg) throws TException {
		throw new TException("ERROR:" + msg);
	}

	@Override
	public void sleep(int time) throws TException {
		ObjectUtil.waitFor(this, time);
	}
}
